Ext.define('Admin.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main',
    alertRequestTimeNumber:60000,//预警数据请求间隔时间，60秒
    listen: {
        controller: {
            '#': {
                unmatchedroute: 'onRouteChange'
            }
        }
    },

    routes: {
        ':node': 'onRouteChange'
    },
    homeConfig:{
        homePageXtype:'viewhomeMain',
        homePhonePageXtype:'viewhomeMainPhone'
    },

    lastView: null,
    homePage:function (btn) {
        if(window.innerWidth < 1030){
            this.redirectTo('#mainMenuPhone');
        }
    },
    openHomeAlertPage:function (btn) {
        this.redirectTo('#pashomemain');
        setTimeout(function () {
            var home = Ext.getCmp('pas-home-page');
            if(home){
                home.activeAlertPanel();
            }
        },10);

    },
    buttonClick:function (btn) {
        this.redirectTo('#'+btn.page);
    },
    requestMenus:function () {
        var me = this;
        App.ux.Ajax.request({
            url: 'auth/getAllMenus',
            success: function (obj) {
                me.addMenuDatas(obj);
            },
            failure: function () {
                Ext.MessageBox.confirm('确认','系统过期或网络异常，请重新登录再重试', function (btn) {
                    if (btn == 'yes') {
                        GTimeOut();
                    }
                });
            }
        });
    },

    addMenuDatas: function (loginDatas) {
        var me = this;
        var myRoot = {};
        var store = Ext.getStore('NavigationTree');
        if (loginDatas && loginDatas.data) {
            var menu = loginDatas.data;
            var root = {children: []};
            me.getMenus(menu, root.children);
            var data = me.getRootData(root, myRoot);
            localStorage.setItem("systemMenus", Ext.encode(data));
            store.setRoot(data);
            if (!window.location.hash) {
                if (window.innerWidth < 1030) {
                    me.redirectTo(this.homeConfig.homePhonePageXtype, true);
                } else {
                    if(store.find('viewType',this.homeConfig.homePageXtype) > 0){
                        me.redirectTo(this.homeConfig.homePageXtype, true);
                    }

                }
            }

        }
    },
    onMainViewRender: function () {
        //隐藏进度条
        $("#loadHTMLprogress2017").attr("style","display:none;");
        $('html,body').css({overflow:'hidden',height:'100%',position:'fixed',left:0,top:0});

        //获取页面菜单
        this.requestMenus();
    },

    setCurrentView: function (hashTag) {
        if(!localStorage.getItem("Authorization")){
            return;
        }
        var me = this,
            i,
            logins = ['login', 'register', 'passwordreset','mainMenuPhone'],
            loginTag = false,
            isPhone = false,
            refs = me.getReferences(),
            mainCard = refs.mainCardPanel,
            mainLayout = mainCard.getLayout(),
            navigationList = refs.navigationTreeList,
            store = navigationList.getStore();
        var root = localStorage.getItem('systemMenus');
        var currentUser = localStorage.getItem('currentUser');
        var currentUserInfo = Ext.decode(currentUser);
        var userInfo = Ext.getCmp('mianView-userInfo');
        var info = '欢迎您';
        //设置欢迎信息
        if (currentUserInfo && userInfo) {
            info ='<i style="color: #fff;" class="x-fa fa-user fa-lg" aria-hidden="true"></i>&ensp;欢迎您，'+ currentUserInfo.userRealName + '';
            userInfo.setText(info);
        }
        //如果浏览器宽度小于1030，使用手机页面布局
        if(window.innerWidth < 1030){
            isPhone = true;
        }
        /*if(!Ext.platformTags.desktop){
            isPhone = true;
        }*/
        var num = store.getCount();
        if (root && num === 0) {
            store.setRoot(Ext.decode(root));
        }
        var node = store.findNode('viewType', hashTag),
            view = (node && node.get('viewType')) || 'page404',
            lastView = me.lastView,
            existingItem = mainCard.child('component[routeId=' + hashTag + ']'),
            newView;

        //登录页面无需限制
        for (i = 0; i < logins.length; i++) {
            if (hashTag == logins[i]) {
                view = hashTag;
                loginTag = true;
            }
        }

        // Kill any previously routed window
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();
        if (!existingItem) {
            if (!loginTag) {
                if(!node){
                    newView = Ext.create({
                        xtype: 'panel',
                        name: 'mainContainer',
                        routeId: hashTag,
                        items: [{
                            xtype: hashTag,
                            //margin: isPhone || !mainCard.tabBar.hidden ? '': '10 10 10 10',
                            cls: mainCard.tabBar.hidden ? 'container-shadow': ''
                        }],
                        closable: true,
                        layout: 'fit',
                        hideMode: 'offsets'
                    });
                }else{
                    newView = Ext.create({
                        xtype: 'panel',
                        name: 'mainContainer',
                        routeId: hashTag,
                        items: [{
                            xtype: view,
                            STARS_MENU_URL: node.data.action,
                            menuConfig: node.data.menuConfig,
                            name: node.get('text'),
                            title: mainCard.tabBar.hidden ? node.get('text') : null,
                            //margin: isPhone || !mainCard.tabBar.hidden ? '': '10 10 10 10',
                            cls: mainCard.tabBar.hidden ? 'container-shadow': ''
                        }],
                        closable: true,
                        title: node.get('text'),
                        layout: 'fit',
                        //lrAuth: node.data.operations,
                        hideMode: 'offsets'
                    });
                }
            } else {
                newView = Ext.create({
                    xtype: view,
                    routeId: hashTag, // for existingItem search later
                    hideMode: 'offsets'
                });
            }
        }

        if (!newView || !newView.isWindow) {
            // !newView means we have an existing view, but if the newView isWindow
            // we don't add it to the card layout.
            if (existingItem) {
                // We don't have a newView, so activate the existing view.
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            } else {
                // newView is set (did not exist already), so add it and make it the
                // activeItem.
                Ext.suspendLayouts();
                mainCard.add(newView);
                mainLayout.setActiveItem(newView);

                Ext.resumeLayouts(true);
            }
        }

        if (newView.isFocusable(true)) {
            newView.focus();
        }

        me.lastView = newView;
        //navigationList.setSelection(node);
    },

    onNavigationTreeSelectionChange: function (tree, node) {
        var to = node && (node.get('routeId') || node.get('viewType'));

        if (this.lastView && this.lastView.routeId == to) {
            if (this.lastView.isDestroyed) {
                this.setCurrentView(to);
            }
            return;
        }
        if (to) {
            this.redirectTo(to);
        }
    },

    tabHide: function (obj) {
        var main = Ext.getCmp('main-view-detail-wrap');
        var tab = main.getComponent('contentPanel');
        var header = tab.tabBar;
        if (header.hidden) {
            header.show();
            obj.setIconCls('x-fa fa-toggle-on');
            obj.setTooltip('隐藏页签栏');
        } else {
            header.hide();
            obj.setIconCls('x-fa fa-toggle-off');
            obj.setTooltip('显示页签栏');
        }
    },

    onToggleNavigationSize: function (btn) {
        if(!btn._clickPress){
            btn._clickPress = true;
        }else{
            btn._clickPress = false;
        }
        this.onToggleMicro(btn,btn._clickPress);
    },
    onToggleMicro: function (button, pressed) {
        var treelist = this.lookupReference('navigationTreeList'),
            navBtn = Ext.getCmp('main-navigation-btn'),
            ct = treelist.ownerCt;
        var dom = Ext.getDom('_home_app_cn_name');
        treelist.setMicro(pressed);

        if (pressed) {
            navBtn.setPressed(true);
            dom.style.display = 'none';
            dom.style.width = '0px';
            navBtn.setStyle({
                left:'54px'
            });
            navBtn.setIconCls('x-fa fa-chevron-right');
            navBtn.setTooltip('收起菜单');
            //navBtn.disable();
            this.oldWidth = treelist.getWidth();
            ct.setWidth(44);
            treelist.setWidth(44);
        } else {
            treelist.setWidth(this.oldWidth);
            ct.setWidth(this.oldWidth);
            navBtn.setIconCls('x-fa fa-chevron-left');
            navBtn.setTooltip('展开菜单');
            dom.style.display = '';
            // dom.style.fontSize = '18px';
            dom.style.width = '80px';
            navBtn.setStyle({
                left: '165px'
            });
        }

        if (Ext.isIE8) {
            treelist.repaintList(treelist, pressed);
        }
        treelist.up('maincontainerwrap').updateLayout();
    },
    getMenus: function (menu, children,parent) {
        var i, temp, icon;
        /*
        通用数据结构
        var a = {
            id: "a69d8760b5f7441c9b2f6f19d46883c7"
            ,perBtnValid: null
            ,perEnabled: null
            ,perIcon: "md-settings"
            ,perName: "系统管理"
            ,perRoutingUrl: ""
            ,perType: "menu"
            ,perUrl: "00"
            ,pid: ""
			,systemPermissionList:[]
		};*/
        for (i = 0; i < menu.length; i++) {
            temp = menu[i];
            if (temp.perType === 'url') {
                continue;
            }
            if (temp.perType === 'btn' && parent) {
                parent.menuConfig.push(temp);
                continue;
            }
            children.push({
                action: temp.perUrl
                , expanded: true
                , children: []
                , iconCls: temp.perIcon
                , id: temp.id
                , leaf: false
                , menuConfig: []
                , name: temp.perName
                , parentId: temp.pid
                , status: 1
                , treeSort: "000001"
                , type: 2
                , viewType: temp.perRoutingUrl
                , buttonFlag: temp.perBtnValid
            });
            if (temp.children && temp.children.length > 0) {
                this.getMenus(temp.children, children[children.length - 1].children,children[children.length - 1]);
            }
            if (temp.perType === 'child') {
                children[children.length - 1].leaf = true;
                children[children.length - 1].type = 3;
            }

        }
    },

    onRouteChange: function (id) {
        this.setCurrentView(id);
    },

    itemdblclick: function (tree, record) {
        if (record.select) {
            this.onNavigationTreeSelectionChange(tree, record.node);
        }
    },

    logout: function () {
        var me = this;
        Ext.MessageBox.confirm('注销确认', '您确定要注销当前用户吗？', function (btn) {
            if (btn == 'yes') {

                LRAjax.request({
                    url: 'auth/logout',
                    success: function (datas) {
                        GTimeOut();
                    }
                });
            }
        });
    },

    aboutSystem: function () {
        if (!document.fullscreenElement && // alternative standard method
            !document.mozFullScreenElement && !document.webkitFullscreenElement) {// current working methods
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        } else {
            if (document.cancelFullScreen) {
                document.cancelFullScreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
        }
    },
    getRootData: function (root, myRoot) {
        var me = this;
        var name = '';
        var isSuccess = false;
        myRoot.text = root.name;
        myRoot.menuConfig = root.menuConfig;

        if (root.menuConfig && root.menuConfig.length === 1) {//长度等于1时，直接获取menuConfig数组中的对象
            myRoot.menuConfig = root.menuConfig[0];
        }


        myRoot.action = root.action;
        myRoot.leaf = root.leaf;
        myRoot.iconCls = root.iconCls;
        if (root.webcof) {//获取webcof的自定义信息
            me.getWebconf(root, myRoot);
        }

        if (root.type == 3) {
            //myRoot.operations = root.children;
            myRoot.viewType = root.viewType;
            if(root.buttonFlag === 'home'){//给home页面添加标签
                myRoot.rowCls = 'nav-tree-badge nav-tree-badge-hot';
                //开启显示预警提示标记,每隔1分钟检测一次
                me.openAlertTag();
                setInterval(function () {
                    me.openAlertTag();
                },me.alertRequestTimeNumber);
            }
            if (myRoot.action && myRoot.viewType) {
                name = root.objectName;
                //动态创建类，如果创建成功返回true
                isSuccess = LRAuto(myRoot.viewType, name);
                if (isSuccess) {
                    myRoot.viewType = name + root.viewType;
                }
            }

        } else {

            myRoot.expanded = true;
            myRoot.selectable = false;

        }

        if (root.children != null) {
            myRoot.children = [];

            for (var i = 0; i < root.children.length; i++) {
                var node = root.children[i];
                var obj = {};
                myRoot.children.push(obj);
                me.getRootData(node, obj);
            }
        }
        return myRoot;
    },
    getWebconf: function (node, myRoot) {
        var webcof = node.webcof;
        var comma = ",";
        var arr = webcof.split(comma);
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];
            var dataArr = obj.split(":");
            var name = dataArr[0];
            var value = dataArr[1];
            myRoot[name] = value;
        }
    },
    openAlertTag:function () {
        App.ux.Ajax.request({
            url: 'pasChartCtl/chartOutDate',
            success: function (response) {
                var data = response.data;
                if(data){
                    $('.nav-tree-badge-hot').append("<style>.nav-tree-badge-hot:after{content: '"+data+"';display: inline;}</style>");
                }else {
                    $('.nav-tree-badge-hot').append("<style>.nav-tree-badge-hot:after{content: '';display: none;}</style>");
                }

            }
        });

    }
});
